;function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
};
function isEmpty(variable) {
	return ((typeof variable == 'undefined')||variable==null||variable.length==0||trim(variable)=='') ? true : false;
};
function isInputEmpty(input) {
	return (isEmpty(input)||isEmpty(input.val())||input.val()==input.attr('placeholder')) ? true : false;
};
function in_array(needle, haystack) {
	if(typeof needle == 'string' || typeof needle == 'number') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
};

function base64_encode (data) {
	  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	  var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
	    ac = 0,
	    enc = "",
	    tmp_arr = [];

	  if (!data) {
	    return data;
	  }

	  do { // pack three octets into four hexets
	    o1 = data.charCodeAt(i++);
	    o2 = data.charCodeAt(i++);
	    o3 = data.charCodeAt(i++);

	    bits = o1 << 16 | o2 << 8 | o3;

	    h1 = bits >> 18 & 0x3f;
	    h2 = bits >> 12 & 0x3f;
	    h3 = bits >> 6 & 0x3f;
	    h4 = bits & 0x3f;

	    // use hexets to index into b64, and append result to encoded string
	    tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	  } while (i < data.length);

	  enc = tmp_arr.join('');

	  var r = data.length % 3;

	  return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

};
function sprintf () {
	  var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
	  var a = arguments,
	    i = 0,
	    format = a[i++];

	  // pad()
	  var pad = function (str, len, chr, leftJustify) {
	    if (!chr) {
	      chr = ' ';
	    }
	    var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
	    return leftJustify ? str + padding : padding + str;
	  };

	  // justify()
	  var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
	    var diff = minWidth - value.length;
	    if (diff > 0) {
	      if (leftJustify || !zeroPad) {
	        value = pad(value, minWidth, customPadChar, leftJustify);
	      } else {
	        value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
	      }
	    }
	    return value;
	  };

	  // formatBaseX()
	  var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
	    // Note: casts negative numbers to positive ones
	    var number = value >>> 0;
	    prefix = prefix && number && {
	      '2': '0b',
	      '8': '0',
	      '16': '0x'
	    }[base] || '';
	    value = prefix + pad(number.toString(base), precision || 0, '0', false);
	    return justify(value, prefix, leftJustify, minWidth, zeroPad);
	  };

	  // formatString()
	  var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
	    if (precision != null) {
	      value = value.slice(0, precision);
	    }
	    return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
	  };

	  // doFormat()
	  var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
	    var number;
	    var prefix;
	    var method;
	    var textTransform;
	    var value;

	    if (substring === '%%') {
	      return '%';
	    }

	    // parse flags
	    var leftJustify = false,
	      positivePrefix = '',
	      zeroPad = false,
	      prefixBaseX = false,
	      customPadChar = ' ';
	    var flagsl = flags.length;
	    for (var j = 0; flags && j < flagsl; j++) {
	      switch (flags.charAt(j)) {
	      case ' ':
	        positivePrefix = ' ';
	        break;
	      case '+':
	        positivePrefix = '+';
	        break;
	      case '-':
	        leftJustify = true;
	        break;
	      case "'":
	        customPadChar = flags.charAt(j + 1);
	        break;
	      case '0':
	        zeroPad = true;
	        break;
	      case '#':
	        prefixBaseX = true;
	        break;
	      }
	    }

	    // parameters may be null, undefined, empty-string or real valued
	    // we want to ignore null, undefined and empty-string values
	    if (!minWidth) {
	      minWidth = 0;
	    } else if (minWidth === '*') {
	      minWidth = +a[i++];
	    } else if (minWidth.charAt(0) == '*') {
	      minWidth = +a[minWidth.slice(1, -1)];
	    } else {
	      minWidth = +minWidth;
	    }

	    // Note: undocumented perl feature:
	    if (minWidth < 0) {
	      minWidth = -minWidth;
	      leftJustify = true;
	    }

	    if (!isFinite(minWidth)) {
	      throw new Error('sprintf: (minimum-)width must be finite');
	    }

	    if (!precision) {
	      precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type === 'd') ? 0 : undefined;
	    } else if (precision === '*') {
	      precision = +a[i++];
	    } else if (precision.charAt(0) == '*') {
	      precision = +a[precision.slice(1, -1)];
	    } else {
	      precision = +precision;
	    }

	    // grab value using valueIndex if required?
	    value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

	    switch (type) {
	    case 's':
	      return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
	    case 'c':
	      return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
	    case 'b':
	      return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
	    case 'o':
	      return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
	    case 'x':
	      return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
	    case 'X':
	      return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
	    case 'u':
	      return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
	    case 'i':
	    case 'd':
	      number = +value || 0;
	      number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
	      prefix = number < 0 ? '-' : positivePrefix;
	      value = prefix + pad(String(Math.abs(number)), precision, '0', false);
	      return justify(value, prefix, leftJustify, minWidth, zeroPad);
	    case 'e':
	    case 'E':
	    case 'f': // Should handle locales (as per setlocale)
	    case 'F':
	    case 'g':
	    case 'G':
	      number = +value;
	      prefix = number < 0 ? '-' : positivePrefix;
	      method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
	      textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
	      value = prefix + Math.abs(number)[method](precision);
	      return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
	    default:
	      return substring;
	    }
	  };

	  return format.replace(regex, doFormat);
};

function trim(str) {
	return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
};

function stripos(haystack, needle, offset) {
	if(isUndefined(offset)) {
		offset = 0;
	}
	var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
};
function strlen(str) {
	return (BROWSER.ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
};

function mb_strlen(str) {
	var len = 0;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
	}
	return len;
};

function mb_cutstr(str, maxlen, dot) {
	var len = 0;
	var ret = '';
	var dot = !dot ? '...' : dot;
	maxlen = maxlen - dot.length;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
		if(len > maxlen) {
			ret += dot;
			break;
		}
		ret += str.substr(i, 1);
	}
	return ret;
};

function preg_replace(search, replace, str, regswitch) {
	var regswitch = !regswitch ? 'ig' : regswitch;
	var len = search.length;
	for(var i = 0; i < len; i++) {
		re = new RegExp(search[i], regswitch);
		str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
	}
	return str;
};
function str_replace (search, replace, subject, count) {
	  var i = 0,
	    j = 0,
	    temp = '',
	    repl = '',
	    sl = 0,
	    fl = 0,
	    f = [].concat(search),
	    r = [].concat(replace),
	    s = subject,
	    ra = Object.prototype.toString.call(r) === '[object Array]',
	    sa = Object.prototype.toString.call(s) === '[object Array]';
	  s = [].concat(s);
	  if (count) {
	    this.window[count] = 0;
	  }

	  for (i = 0, sl = s.length; i < sl; i++) {
	    if (s[i] === '') {
	      continue;
	    }
	    for (j = 0, fl = f.length; j < fl; j++) {
	      temp = s[i] + '';
	      repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
	      s[i] = (temp).split(f[j]).join(repl);
	      if (count && s[i] !== temp) {
	        this.window[count] += (temp.length - s[i].length) / f[j].length;
	      }
	    }
	  }
	  return sa ? s : s[0];
};
function htmlspecialchars(str) {
	return preg_replace(['&', '<', '>', '"'], ['&amp;', '&lt;', '&gt;', '&quot;'], str);
};
function _attachEvent(obj, evt, func, eventobj) {
	eventobj = !eventobj ? obj : eventobj;
	if(obj.addEventListener) {
		obj.addEventListener(evt, func, false);
	} else if(eventobj.attachEvent) {
		obj.attachEvent('on' + evt, func);
	}
};

function _detachEvent(obj, evt, func, eventobj) {
	eventobj = !eventobj ? obj : eventobj;
	if(obj.removeEventListener) {
		obj.removeEventListener(evt, func, false);
	} else if(eventobj.detachEvent) {
		obj.detachEvent('on' + evt, func);
	}
};
function doane(event, preventDefault, stopPropagation) {
	var preventDefault = isUndefined(preventDefault) ? 1 : preventDefault;
	var stopPropagation = isUndefined(stopPropagation) ? 1 : stopPropagation;
	e = event ? event : window.event;
	if(!e) {
		e = getEvent();
	}
	if(!e) {
		return null;
	}
	if(preventDefault) {
		if(e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
	}
	if(stopPropagation) {
		if(e.stopPropagation) {
			e.stopPropagation();
		} else {
			e.cancelBubble = true;
		}
	}
	return e;
};

function isEmail(email) {
	return email.length > 6 && /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(email);
};
function squarestrip(str) {
	str = str.replace('[', '%5B');
	str = str.replace(']', '%5D');
	return str;
};

function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
	var expires = new Date();
	if(cookieValue == '' || seconds < 0) {
		cookieValue = '';
		seconds = -2592000;
	}
	expires.setTime(expires.getTime() + seconds * 1000);
	domain = !domain ? cookiedomain : domain;
	path = !path ? cookiepath : path;
	document.cookie = escape(cookiepre + cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '/')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};

function getcookie(name, nounescape) {
	name = cookiepre + name;
	var cookie_start = document.cookie.indexOf(name);
	var cookie_end = document.cookie.indexOf(";", cookie_start);
	if(cookie_start == -1) {
		return '';
	} else {
		var v = document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length));
		return !nounescape ? unescape(v) : v;
	}
};
function getcookiearray(){
	var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value;
	var postParams = [];
	for (i = 0; i < caLength; i++) {
		c = cookieArray[i];
		
		// Left Trim spaces
		while (c.charAt(0) === " ") {
			c = c.substring(1, c.length);
		}
		eqIndex = c.indexOf("=");
		if (eqIndex > 0) {
			name = c.substring(0, eqIndex);
			value = c.substring(eqIndex + 1);
			postParams[name] = value;
		}
	}
	return postParams;
}
function TWinOpen(url, id, iWidth, iHeight) {
	var iTop = (screen.height - 30 - iHeight) / 2; // 获得窗口的垂直位置;
	var iLeft = (screen.width - 10 - iWidth) / 2; // 获得窗口的水平位置;
	TWin = window.showModalDialog(url, null, "dialogWidth=" + iWidth
			+ "px;dialogHeight=" + iHeight + "px;dialogTop=" + iTop
			+ "px;dialogLeft=" + iLeft + "px");
};

function iFrameHeight(frame) {
	var ifm = $(frame);
	var subWeb = document.frames ? document.frames[frame].document
			: ifm.contentDocument;
	if (ifm != null && subWeb != null) {
		ifm.height = subWeb.body.scrollHeight;
	}
};
function random(length) {
	var charactors = "ab1cd2ef3gh4ij5kl6mn7opq8rst9uvw0xyz";
	var value = '', i;
	for ( var j = 1; j <= length; j++) {
		i = parseInt(35 * Math.random());
		value = value + charactors.charAt(i);
	}
	return value;
};

function mb_cutstr(str, maxlen, dot) {
	var len = 0;
	var ret = '';
	var dot = '';
	maxlen = maxlen - dot.length;
	for ( var i = 0; i < str.length; i++) {
		len++;
		if (str.charCodeAt(i) > 127) {
			len++;
		}
		if (len > maxlen) {
			ret += dot;
			break;
		}
		ret += str.substr(i, 1);
	}
	return ret;
};
function strLenCalc(obj, checklen, maxlen) {
	var v = obj.value, curlen = maxlen, len = str_length(v);
	if (curlen >= len) {
		$('#' + checklen).html(curlen - len);
	} else {
		obj.value = mb_cutstr(v, maxlen, 0);
	}
};

function getTip(type){
	var tips = $("#data-tips");
	var message = tips.attr('data-'+type);
	if(message!=null&&message!=undefined&&message!=='')
		return message;
	return type;
};

//reward,alert
function check_message(event,autohide,time,waittime){
	$.ajax({
		type: "get",
		url: url_checkmessage,
		dataType: 'json',
		data: {'event': event,'radom': random(3)}
	}).error(function() {
		if(js_debug){
			show_message('error',tip_error+' check_message: '+tip_server_error,false,0);
		}
	}).success(function(result) {
		if (result.success === !0) {
			var data = result.data;
			var type = result.message;
			if(type=='tip'){
				for(var i=0;i<data.length;i++){
					var msg = data[i];
			        setTimeout(function() {
			        	show_message(type,msg,autohide,time);
					}, waittime);
			    }
			}else if(type=='user_message'){
				$('#message_num_container').html(data.message_html);
				setTimeout(function() {
					check_message('user_message',false,0,0);
				}, 300000);
			}else if(type=='alert'){
				$('#alert_num_container').html(data.message_html);
				setTimeout(function() {
					check_message('alert',false,0,0);
				}, 250000);
			}
		} else {
			show_message(result.message);
		}
	});
};

//tip,success,error,danger,info
function show_message(type,message,autohide,time){
	var messageDialog = $.oDialog('messageDialog', {
		id: 'ui_message_dialog',
		width : '100',
		center : true,
		mask : false,
		close : !autohide,
		className : 'ui-message',
		tpl : '<div id="%ID" class="%CLASSNAME"><button type="button" class="close">×</button><div class="bd"><div class="ui-loading">loading...</div></div></div>'
	});
	var message_length = (message + '').replace(/<script.*?>.*?<\/script>/ig, '').replace(/<a[^>]+>/ig, '').replace(/<\/a>/ig, '');
	var str_width = str_length(message_length)*8+30;
	var d_width = str_width>500?500:str_width;
	d_width = d_width<170?170:d_width;
	messageDialog.width(d_width).body(message);
	messageDialog.elem.attr("class","ui-message message-"+type); 
	messageDialog.config.close = !autohide;
	messageDialog.show();
	if(autohide){
		setTimeout(function() {
			messageDialog.hide();
		}, time);
	}
};
function show_loading(type){
	var loadingDialog = $.oDialog('uloadingDialog', {
		id: 'ui_loading_dialog',
		width : '250',
		center : true,
		mask : false,
		close : false,
		className : 'ui-message',
		tpl : '<div id="%ID" class="%CLASSNAME"><button type="button" class="close">×</button><div class="bd progress progress-striped active"><div class="bar" style="width:20%;"></div></div></div>'
	});
	loadingDialog.width(280);
	loadingDialog.elem.attr("class","ui-message progress-"+type); 
	//loadingDialog.elem.addClass('progress-'+type);
	loadingDialog.elem.find('.bar').css('width','50%');
	loadingDialog.show();
};

function hide_loading(){
	var loadingDialog = $.oFDialog('uloadingDialog');
	if(loadingDialog){
		setTimeout(function() {loadingDialog.elem.find('.bar').css('width','100%');}, 500);
		setTimeout(function() {loadingDialog.hide();loadingDialog.elem.find('.bar').css('width','20%');}, 1000);
	}
};
function checkredirect(e){
	var  re, matches, url;
	re = /content='0;url=([^']+)'/i;
	matches = re.exec(e.responseText);
	if(matches != null) {
		url = matches[1];
		window.location.href = url;
	}else{
		if(js_debug){
			show_message('error',tip_error+' ajaxerror: '+e.responseText,false,0);
		}
	}
};
function ajaxpost(posturl,postdata,successFunc,failedFunc){
	show_loading('success');
	$.ajax({
		type: "post",
		url: posturl,
		dataType: 'json',
		data: postdata
	}).error(function(e) {
		checkredirect(e);
		hide_loading();
		/*if(js_debug){
			show_message('error',tip_error+' ajaxpost: '+posturl,false,0);
		}*/
	}).success(function(result) {
		hide_loading();
		if (result.success === !0) {
			successFunc.call(postdata, result);
		} else {
			if($.trim(result.message) == "not_login") {
				openLoginDialog();
				return;
			}
			failedFunc.call(postdata, result);
		}
	});
};

function ajaxget(posturl,postdata,successFunc,failedFunc){
	//show_loading('success');
	$.ajax({
		type: "get",
		url: posturl,
		dataType: 'json',
		data: postdata
	}).error(function(e) {
		checkredirect(e);
		/*if(js_debug){
			show_message('error',tip_error+' ajaxget: '+posturl,false,0);
		}*/
	}).success(function(result) {
		if (result.success === !0) {
			successFunc.call(postdata, result);
		} else {
			if($.trim(result.message) == "not_login") {
				openLoginDialog();
				return;
			}
			failedFunc.call(postdata, result);
		}
	});
};
function fetchAjaxTpl(id,func){
	ajaxget(url_fetchtpl,{'tpl': id},
			function(result){
				wrapTpl(result.data.tpl,id+"_tpl");
				if(func!=null) func.call();
			},
			function(result){
			});
};

function showDialog(id,func){
	if(document.getElementById(id+'_tpl') == null){
		fetchAjaxTpl(id,function (){
			showTpl(id);
			if(func!=null) func.call();
		});
	}else{
		showTpl(id);
		if(func!=null) func.call();
	}
};

function getStaticDialog(){
	var staticDialog = $.oDialog('puzzDialog', {
		id: 'ui_puzz_dialog'
	});
	$(staticDialog).bind("hide",function() {
		if (!isUndefined(crop_image)&&crop_image!=null) crop_image.remove();
		$('.tooltip').remove();
	});
	$(staticDialog).bind("show",function() {
		if (!isUndefined(crop_image)&&crop_image!=null) crop_image.remove();
		$('.tooltip').remove();
	});
	return staticDialog;
};

function showTpl(id){
	var show_tpl = $('#'+id+'_tpl');
	var body = $(show_tpl.html()).find('div.pbody');
	var footer = $(show_tpl.html()).find('div.footer');
	var width = body.attr('data-width');
	var title = body.attr('data-title');
	var css = body.attr('data-css-class');
	var d=getStaticDialog().width(width).head(title).body(body);
	if(footer.val()!=null) d.footer(footer.html());
	d.elem.addClass(css);
	d.show();
};
function getTpl(id,func){
	if(document.getElementById(id+'_tpl') == null){
		fetchAjaxTpl(id,function (){
			if(func!=null) func.call();
		});
	}else{
		if(func!=null) func.call();
	}
};
function fetchAjaxCount(){
	ajaxget(url_fetchtpl,{'tpl': 'footer_count'},
			function(result){
				$('#footer-counter').html(result.data.tpl);
			},
			function(result){
			});
};

function wrapTpl(tpl,id){
	var outer = "<script type=\"text/template\" id=\""+id+"\">"+tpl+"</script>";
	$('#body').append(outer);
};

function openLoginDialog(func) {
	showDialog('login_box',function(){
		$.oValidate('login_form');
		$.oValidate('bbs_login_form');
		if(func!=null&&!isUndefined(func))
			func.call();
	});
};

function showSuccess(message,redirect){
	show_message('success',tip_success+': '+message,true,5000);
	if(redirect!=null){
		if(redirect==true){
			window.location.reload();
		}else{
			window.location.href = redirect;
		}
	}
};

function showInfo(message){
	show_message('info',message,false,0);
};

function showError(message) {
	if ($.trim(message) == "not-login") {
		openLoginDialog();
	} else if (message != null) {
		show_message('error',tip_error+': '+$.trim(message),false,0);
	} else {
		show_message('error',tip_error+': '+tip_server_error,false,0);
	}
};

function str_length(value) {
	var length = value.length;
	for ( var i = 0; i < value.length; i++) {
		if (value.charCodeAt(i) > 127) {
			length++;
		}
	}
	return length;
};
var imageReady = (function() {
	var list = [], timer = null, prop = [ [ 'width', 'height' ],
			[ 'naturalWidth', 'naturalHeight' ] ], natural = Number(typeof document
			.createElement('img').naturalHeight === 'number'), // 是否支持HTML5新增的
	// naturalHeight
	tick = function() {
		for ( var i = 0; i < list.length; i++) {
			list[i].end ? list.splice(i--, 1) : check.call(list[i], null);
		}
		list.length && (timer = setTimeout(tick, 50)) || (timer = null);
	},
	/**
	 * overflow: 检测图片尺寸的改变 img.__width,img.__height: 初载入时的尺寸
	 */
	check = function() {
		if (this[prop[natural][0]] !== this.__width
				|| this[prop[natural][1]] !== this.__height
				|| this[prop[natural][0]] * this[prop[natural][1]] > 1024) {
			this.onready.call(this, null);
			this.end = true;
		}
	};
	return function(_img,r_url, onready, onload, onerror) {
		r_url = r_url || '';
		onready = onready || new Function(r_url);
		onload = onload || new Function(r_url);
		onerror = onerror || new Function(r_url);
		var img = typeof _img == 'string' ? new Image() : _img;
		img.onerror = function() {// ie && ie<=8 的浏览器必须在src赋予前定义onerror
			onerror.call(img, r_url);
			img.end = true;
			img = img.onload = img.onerror = img.onreadystatechange = null;
		};
		if (typeof _img == 'string')
			img.src = _img;
		if (!img)
			return;
		img.__width = img[prop[natural][0]];
		img.__height = img[prop[natural][1]];
		if (img.complete) {
			onready.call(img, r_url);
			onload.call(img, r_url);
			return;
		}
		img.onready = function(){onready.call(img, r_url);};
		check.call(img, null);
		img.onload = img.onreadystatechange = function() {
			if (img && img.readyState && img.readyState != 'loaded'
					&& img.readyState != 'complete') {
				return;
			}
			!img.end && check.call(img, null);
			onload.call(img, r_url);
			img = img.onload = img.onerror = img.onreadystatechange = null;
		};
		if (!img.end) {
			list.push(img);
			if (timer === null)
				timer = setTimeout(tick, 50);
		}
	};
})();

function preloadImages(images, onready, onload, onerror, callback) {
	callback = callback || new Function();
	onready = onready || new Function();
	onerror = onerror || new Function();
	onload = onload || new Function();
	var count = images.length;
	if (count === 0) {
		callback.call(images, null);
	}
	var loaded = 0;
	for ( var i = 0; i < count; i++) {
		var img = images[i];
		imageReady(img, function() {
			// loaded++;
			onready.call(this, null);
			if (i == count) {
				callback.call(images, null);
			}
		}, function() {
			onload.call(this, null);
		}, function() {
			// loaded++;
			onerror.call(this, null);
			if (i == count) {
				callback.call(images, null);
			}
		});
	}

	/*
	 * $(images).each(function() { imageReady(this, function() { loaded++;
	 * onready.call(this, null); if (loaded == count) { callback.call(images,
	 * null); } },function() { onload.call(this, null); }, function() {
	 * loaded++; onerror.call(this, null); if (loaded == count) {
	 * callback.call(images, null); } }); });
	 */
	// alert(count);
};
/*
 * function preloadImages(images, callback) { var count = images.length;
 * if(count === 0) { callback(); } var loaded = 0; $(images).each(function() {
 * imageReady(this, function() { loaded++; if (loaded === count) { callback(); }
 * }); }); };
 */
$.fn.extend({
	insertAtCaret : function(myValue, needSelect) {
		return this.each(function(i) {
			if (document.selection) {
				// For browsers like Internet Explorer
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				if (needSelect) {
					sel.moveStart("character", -(myValue.length - 1));
					sel.moveEnd("character", -1);
					sel.select();
				}
			} else if (this.selectionStart || this.selectionStart == '0') {
				// For browsers like Firefox and Webkit based
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos) + myValue
						+ this.value.substring(endPos, this.value.length);
				this.focus();

				if (needSelect) {
					this.selectionStart = startPos + 1;
					this.selectionEnd = startPos + myValue.length - 1;
				} else {
					this.selectionStart = startPos + myValue.length;
					this.selectionEnd = startPos + myValue.length;
				}
				this.scrollTop = scrollTop;
			} else {
				this.value += myValue;
				this.focus();
			}
		});
	}
});
function utf8_encode(argString) {
	if (argString === null || typeof argString === "undefined") {
		return "";
	}

	var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g,
									// "\n");
	var utftext = "", start, end, stringl = 0;

	start = end = 0;
	stringl = string.length;
	for ( var n = 0; n < stringl; n++) {
		var c1 = string.charCodeAt(n);
		var enc = null;

		if (c1 < 128) {
			end++;
		} else if (c1 > 127 && c1 < 2048) {
			enc = String.fromCharCode((c1 >> 6) | 192)
					+ String.fromCharCode((c1 & 63) | 128);
		} else {
			enc = String.fromCharCode((c1 >> 12) | 224)
					+ String.fromCharCode(((c1 >> 6) & 63) | 128)
					+ String.fromCharCode((c1 & 63) | 128);
		}
		if (enc !== null) {
			if (end > start) {
				utftext += string.slice(start, end);
			}
			utftext += enc;
			start = end = n + 1;
		}
	}

	if (end > start) {
		utftext += string.slice(start, stringl);
	}

	return utftext;
};
function serialize(mixed_value) {
	var _utf8Size = function(str) {
		var size = 0, i = 0, l = str.length, code = '';
		for (i = 0; i < l; i++) {
			code = str.charCodeAt(i);
			if (code < 0x0080) {
				size += 1;
			} else if (code < 0x0800) {
				size += 2;
			} else {
				size += 3;
			}
		}
		return size;
	};
	var _getType = function(inp) {
		var type = typeof inp, match;
		var key;

		if (type === 'object' && !inp) {
			return 'null';
		}
		if (type === "object") {
			if (!inp.constructor) {
				return 'object';
			}
			var cons = inp.constructor.toString();
			match = cons.match(/(\w+)\(/);
			if (match) {
				cons = match[1].toLowerCase();
			}
			var types = [ "boolean", "number", "string", "array" ];
			for (key in types) {
				if (cons == types[key]) {
					type = types[key];
					break;
				}
			}
		}
		return type;
	};
	var type = _getType(mixed_value);
	var val, ktype = '';

	switch (type) {
	case "function":
		val = "";
		break;
	case "boolean":
		val = "b:" + (mixed_value ? "1" : "0");
		break;
	case "number":
		val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":"
				+ mixed_value;
		break;
	case "string":
		val = "s:" + _utf8Size(mixed_value) + ":\"" + mixed_value + "\"";
		break;
	case "array":
	case "object":
		val = "a";
		/*
		 * if (type == "object") { var objname =
		 * mixed_value.constructor.toString().match(/(\w+)\(\)/); if (objname ==
		 * undefined) { return; } objname[1] = this.serialize(objname[1]); val =
		 * "O" + objname[1].substring(1, objname[1].length - 1); }
		 */
		var count = 0;
		var vals = "";
		var okey;
		var key;
		for (key in mixed_value) {
			if (mixed_value.hasOwnProperty(key)) {
				ktype = _getType(mixed_value[key]);
				if (ktype === "function") {
					continue;
				}

				okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
				vals += this.serialize(okey) + this.serialize(mixed_value[key]);
				count++;
			}
		}
		val += ":" + count + ":{" + vals + "}";
		break;
	case "undefined":
		// Fall-through
	default:
		// if the JS object has a property which contains a null value, the
		// string cannot be unserialized by PHP
		val = "N";
		break;
	}
	if (type !== "object" && type !== "array") {
		val += ";";
	}
	return val;
};
//*********************pz data functions

function afterDeleteShare(result){
	getStaticDialog().hide();;
	var sid = result.data.share_id;
	$('#' + sid).fadeTo(1000, "hide", 0);
	setTimeout(function() {
		$('#waterfall').masonry('remove', $('#' + sid));
		$('#waterfall').masonry('reload');
		$('#timeline-box').masonry('remove', $('#' + sid));
		$('#timeline-box').masonry('reload',function(){resetArrow();});
	},
	1000);
}

function resetArrow() {
	var $container = $('#timeline-box');
	var s = $container.find('.timeline');
	$.each(s, function(i, obj) {
		appendArrow(obj);
	});
	var line = $container.find('.line');
	var height = $container.height();
	$(line).css('height',height);
}

function appendArrow(obj){
	var posLeft = $(obj).css("left");
	var con = $(obj).find('.corner');
	var html='';
	if (posLeft == "0px"||posLeft == "auto") {
		html = "<span class='right-line'><i class='right-corner'></i><i class='pointer'></i></span>";
	} else {
		html = "<span class='left-line'><i class='left-corner'></i><i class='pointer'></i></span>";
	}
	$(con).html(html);
}
function addLike(type, sid, appendId, purl, parent) {
	if(parent)
		parent.addClass('processing');
	var postdata;
	if(type=='share'){
		postdata = {'sid': sid};
	}else if(type=='album'){
		postdata = {'aid': sid};
	}else if(type=='topic'){
		postdata = {'topicid': sid};
	}else if(type=='store'){
		postdata = {'storeid': sid};
	}
	ajaxget(purl, postdata, 
			function(result){
				if(parent){
					parent.addClass('meta-liked');
				}
				$('#' + appendId).append('<div id="'+sid+'_like_added" class="like_add">'+tip_addlike+'</div>');
				$('#'+sid+'_like_added').fadeTo(3000, "hide", 0);
				setTimeout(function() {
					$('#'+sid+'_like_added').remove();
				},3000);
				var likenum = $('#'+sid+'_likenum').find('em').text();
				$('#'+sid+'_likenum').find('em').text(Number(likenum)+1);
				$('#'+sid+'_addlikebtn').addClass('hide');
				$('#'+sid+'_removelikebtn').removeClass('hide');
				check_message('reward',true,3000,700);
				if(parent)
					parent.removeClass('processing');
			},
			function(result){
				if ($.trim(result.message) == "like_already") {
					$('#' + appendId).append('<div id="'
					 + sid
					 + '_like_already" class="like_already">'+tip_likealready+'</div>');
					$('#' + sid + '_like_already').fadeTo(3000, "hide", 0);
					setTimeout(function() {
						$('#' + sid + '_like_already').remove();
					},
					3000);
				} else if ($.trim(result.message) == "like_self") {
					$('#' + appendId).append('<div id="'
					 + sid
					 + '_like_self" class="like_self">'+tip_likeself+'</div>');
					$('#' + sid + '_like_self').fadeTo(3000, "hide", 0);
					setTimeout(function() {
						$('#' + sid + '_like_self').remove();
					},
					3000);
				} else {
					showError(result.message);
				}
				if(parent)
					parent.removeClass('processing');
			});
};
function removeAlbum(aid, appendId, purl) {
	var postdata = {'aid': aid};
	ajaxpost(purl, postdata, 
			function(result){
				$('#' + appendId).fadeTo(1000, "hide", 0);
				setTimeout(function() {
					$('#waterfall').masonry('remove', $('#' + appendId));
					$('#waterfall').masonry('reload');
				},
				1000);
			},
			function(result){
				showError(result.message);
			});
};

function removeLike(type, sid, appendId, purl) {
	var postdata;
	if(type=='share'){
		postdata = {'sid': sid};
	}else if(type=='album'){
		postdata = {'aid': sid};
	}else if(type=='topic'){
		postdata = {'topicid': sid};
	}else if(type=='store'){
		postdata = {'storeid': sid};
	}
	
	ajaxget(purl, postdata, 
			function(result){
				$('#' + appendId).append('<div id="'+ sid + '_like_added" class="like_add">'+tip_removedlike+'</div>');
				$('#' + sid + '_like_added').fadeTo(3000, "hide", 0);
				setTimeout(function() {
					$('#' + sid + '_like_added').remove();
				},
				3000);
				var likenum = $('#' + sid + '_likenum').find('em').text();
				if(Number(likenum)>0)
				$('#'+ sid + '_likenum').find('em').text(Number(likenum) - 1);

				$('#'+sid+'_addlikebtn').removeClass('hide');
				$('#'+sid+'_removelikebtn').addClass('hide');
				if(type=='album'){
					var reload = $('#'+sid+'_removelikebtn').attr('data-reload');
					if(reload=='true'){
						setTimeout(function() {
							$('#' + appendId).fadeTo(1000, "hide", 0);
						},
						3000);
						setTimeout(function() {
							$('#waterfall').masonry('remove', $('#' + appendId));
							$('#waterfall').masonry('reload');
						},
						4000);
					}
					
				}
			},
			function(result){
				showError(result.message);
			});
};

function getTags(cat_id,div_id){
	var div_elem = $(div_id);
	var data= {'cid':cat_id,'radom': random(5)};
	ajaxget(url_listcategory_tags, data, 
			function(result){
				var target_id = div_elem.attr('data-target-id');
				var maxselected = div_elem.attr('data-maxselected');
				var lis = $(Mustache.render('{{#data}}<li><a href="javascript:;" class="box">{{.}}</a></li>{{/data}}', result));
				div_elem.html(lis);
				$(div_elem).clickSelectedTo({
					selectedclass:'selected',
					insertpath:'>a',
					maxselected:maxselected,
					targetarea:target_id
				});
			},
			function(result){
				div_elem.html('');
			});
};

function albumSelect(aid, a_title,div_id) {
	var div_elem = $('#' + div_id);
	var elem = div_elem.find('.album_select_list');
	if (elem.hasClass("btn_select_hover")) {
		elem.removeClass("btn_select_hover");
	}
	var find = false;
	if(aid!=null){
		elem.find('li').each(function() {
            var data_id = $(this).find('a').attr('data-aid');
            if(aid==data_id){
            	find=true;
    			return;
            }
        });
	}
	if(find){
		elem.find('.album_select_title').html(a_title);
		elem.find('.album_select_id').val(aid);
	}else{
		elem.find('.album_select_title').html(tip_select);
		elem.find('.album_select_id').val('');
	}
	
};

function getAlbums(div_id,cid, aid, a_title) {
	var data_actions = $('#data-actions');
	var div_elem = $('#' + div_id);
	var album_div = div_elem.find('.album_select_list');
	var ul = album_div.find("ul");
	var uid = div_elem.attr('data-uid');
	
	var data= {'cid':cid,'uid':uid,'radom': random(5)};
	ajaxget(url_useralbums, data, 
			function(result){
				var lis = $(Mustache.render('{{#data}}<li><a href="javascript:;" data-aid="{{album_id}}" data-action="albumItem" data-params="{{album_id}},{{album_title}},'+div_id+'">{{album_title}}</a></li>{{/data}}', result));
				ul.html(ul.children(":last"));
				lis.insertBefore(ul.children(":last"));
				if (aid == null || aid == undefined || a_title == null || a_title == undefined) {
					albumSelect(result.data[0].album_id, result.data[0].album_title,div_id);
				} else {
					albumSelect(aid, a_title,div_id);
				}
				album_div.attr("data-init", 1);
			},
			function(result){
				var last = ul.children(":last");
				ul.html(last);
				albumSelect(null, null,div_id);
			});
};
function getCategories(div_id, cat_id, cat_name) {
	var div_elem = $('#' + div_id);
	var cat_div_id = div_elem.find('.category_select_list');
	var inited = cat_div_id.attr("data-init");
	var find_album = cat_div_id.attr("data-find-album");
	if (inited != '0') {
		return;
	}
	var ul = cat_div_id.find("ul");
	var data= {'radom': random(5)};
	ajaxget(url_categorylist, data, 
			function(result){
				var lis = $(Mustache.render('{{#data}}<li><a href="javascript:;" data-action="categoryItem" data-params="{{category_id}},{{category_name_cn}},'+div_id+','+find_album+'">{{category_name_cn}}</a></li>{{/data}}', result));
				ul.prepend(lis);
				if (cat_id == null || cat_id == undefined || cat_name == null || cat_name == undefined) {
					categorySelect(result.data[0].category_id, result.data[0].category_name_cn,div_id,find_album);
				} else {
					categorySelect(cat_id, cat_name,div_id,find_album);
				}
				cat_div_id.attr("data-init", 1);
			},
			function(result){
				showError(result.message);
			});
};
function categorySelect(cat_id, cat_name_cn,div_id,find_album) {
	var div_elem = $('#' + div_id);
	var cat_div_id = div_elem.find('.category_select_list');
	if (cat_div_id.hasClass("btn_select_hover")) {
		cat_div_id.removeClass("btn_select_hover");
	}
	
	cat_div_id.find('.category_select_title').html(cat_name_cn);
	cat_div_id.find('.category_select_id').val(cat_id);
	if(find_album!=0&&find_album!=null&&find_album!=''&&find_album!=undefined){
		var album_div_id = div_elem.find('.album_select_list');
		if(album_div_id){
			var album_id = album_div_id.attr('data-album-id');
			var album_name = album_div_id.attr('data-album-name');
			getAlbums(div_id,cat_id,album_id,album_name);
		}else{
			getAlbums(div_id,cat_id,null,null);
		}
	}
	var tag_list = div_elem.find('.tags_list');
	if(tag_list){
		getTags(cat_id,tag_list);
	}
};
function createAlbumItem(div_id,uid) {
	var div_elem = $('#' + div_id);
	var a_name_elem = div_elem.find('.album_name');
	var cat_input_id = div_elem.find('.category_select_id');
	var data= {'album_title': a_name_elem.val(),
			'category_id': cat_input_id.val(),
			'uid': uid};
	ajaxpost(url_createalbum, data, 
			function(result){
				var lis = $(Mustache.to_html('{{#data}}<li><a href="javascript:;" data-aid="{{album_id}}" data-action="albumItem" data-params="{{album_id}},{{album_title}},'+div_id+'">{{album_title}}</a></li>{{/data}}', result));
				lis.insertBefore(a_name_elem.parent());
				albumSelect(result.data.album_id, result.data.album_title,div_id);
				a_name_elem.val('');
			},
			function(result){
				showError(result.message);
			});
};